< previous page page_168 next page >

Page 168
Keeping a Variable Local
If you do not need to access a variable from everywhere in your program, you should not use the Public keyword in a declaration. Instead, you should use the Dim or Private keywords, which tell Visual Basic to define the variable within the scope of the current procedure or form, respectively. With these declarations, the location of the statement determines the actual scope of the variable. If the variable is defined in the General Declarations section of a form or module, the variable is available to every procedure in that form or module. This type is known as a form-level or module-level variable. If the variable is declared inside a procedure, it can be used only within that procedure. This type is typically known as a local variable.
You may be wondering the reasons behind wanting to keep a variable as local as possible. The answer is two-fold:
Good Programming Practice. Having code that relies on a public variable is harder to debug and maintain. For example, consider the following implementations of a simple procedure, CalcArea:
Sub CalcArea()
               MsgBox "The Answer is " & nHeight * nWidth
End Sub

Sub CalcArea(nHeight As Integer, nWidth As Integer)

               MsgBox "The Answer is " & nHeight * nWidth
End Sub
If you are tasked with debugging the CalcArea procedure, the first example is the most difficult. The calculation depends on two public variables (nHeight and nWidth) being set correctly. The second implementation improves on this problem slightly by making nHeight and nWidth function parameters, allowing the programmer to easily call the function from the Immediate window without having to preset many variables. Of course, to make CalcArea as modular and reusable as possible, you would probably want to turn it into a function.
Use of Resources. The second reason for keeping variables as local as possible should be almost common sense. If you declare a variable as Public, Visual Basic has to make that variable available to all forms and modules in your application. The limited scope of local variables does not require as many resources and will make your programs more efficient.
Using Static Variables
Most variables that are created inside a procedure are discarded by Visual Basic when the procedure is finished. Sometimes, however, you might want to preserve the value of a variable even after the procedure has run. This is often the case when you call the procedure multiple times, and the value of a variable for one call to the procedure is dependent on the value left over from previous calls. As an example, you may have a procedure that prints a header at the top of each page of a report, and the procedure needs to remember the page number from the previous time it was called so that it can be incremented.

 
< previous page page_168 next page >